<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    style="height: 100%;overflow: auto;padding-bottom: 53px;">

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-card title="用户基本信息" :bordered="false">
          <a-row>
            <a-col :span="colSpan">
              <a-form-item label="账号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入账号" v-decorator.trim="[ 'username', validatorRules.username]" :disabled="disableSubmit"/>
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="姓名" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入姓名" v-decorator.trim="[ 'realname', validatorRules.realname]" :disabled="disableSubmit"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-show="!disableSubmit">
            <a-col :span="colSpan">
              <a-form-item label="初始密码" :labelCol="labelCol" :wrapperCol="wrapperCol" >
                <a-input-password type="password" placeholder="请输入初始密码" v-decorator="[ 'password',validatorRules.password]" v-if="showPassword"/>
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="确认密码" :labelCol="labelCol" :wrapperCol="wrapperCol" >
                <a-input-password type="password" @blur="handleConfirmBlur" placeholder="请重新输入登录密码" v-decorator="[ 'confirmpassword', validatorRules.confirmpassword]" v-if="showPassword"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="colSpan">
              <a-form-item label="手机号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入手机号码" v-decorator="[ 'phone', validatorRules.phone]" :disabled="disableSubmit" />
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="性别" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-dict-select-tag placeholder="请选择性别" :triggerChange="true" v-decorator="['sex']" dictCode="sex" :disabled="disableSubmit"></j-dict-select-tag>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="colSpan">
              <a-form-item label="座机号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入座机号" v-decorator="[ 'telephone', validatorRules.telephone]" :disabled="disableSubmit" />
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="邮箱" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入邮箱" v-decorator="[ 'email', validatorRules.email]" :disabled="disableSubmit" />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="colSpan">
              <a-form-item label="生日" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-date-picker
                  :disabled="disableSubmit"
                  style="width: 100%"
                  placeholder="请选择生日"
                  v-decorator="['birthday']"
                  :getCalendarContainer="node => node.parentNode"/>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        <a-card title="关联组织" :bordered="false">
          <a-row>
            <a-col :span="colSpan">
              <a-form-item :label="'组织名称'" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select
                  :disabled="disableSubmit"
                  style="width: 100%"
                  showSearch
                  optionFilterProp="children"
                  :autoClearSearchValue="false"
                  v-decorator="['tenantId', validatorRules.tenant]"
                  @change="changeTenant($event)"
                  :getPopupContainer="(target) => target.parentNode">
                  <a-select-option v-for="(item, index) in tenantList" :key="index" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="工号" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-input placeholder="请输入工号" v-decorator.trim="['workNo',validatorRules.workNo]" :disabled="disableSubmit"/>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="colSpan">
              <a-form-item label="部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-tree-select
                  :disabled="disableSubmit"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '500px', overflow: 'auto' }"
                  placeholder="请选择部门"
                  showSearch
                  treeNodeFilterProp="title"
                  allow-clear
                  treeDefaultExpandAll
                  :tree-data="departTreeData"
                  v-decorator="['departId', validatorRules.depart]"
                  :getPopupContainer="(target) => target.parentNode"
                  :multiple="true"
                  @change="(departId, label, extra) => changeDepart(departId, label)">
                </a-tree-select>
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="负责部门" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select
                  :disabled="disableSubmit"
                  style="width: 100%"
                  :dropdown-style="{ maxHeight: '500px', overflow: 'auto' }"
                  placeholder="请选择负责部门"
                  allow-clear
                  treeDefaultExpandAll
                  mode="multiple"
                  :getPopupContainer="(target) => target.parentNode"
                  :options="departsTreeData"
                  v-decorator="['departIds']">
                </a-select>
              </a-form-item>

            </a-col>
          </a-row>
          <a-row>
            <a-col :span="colSpan">
              <a-form-item label="头像" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-image-upload class="appIconFile-uploader" text="上传" v-decorator="['avatar']" :disabled="disableSubmit"></j-image-upload>
              </a-form-item>
            </a-col>
            <a-col :span="colSpan">
              <a-form-item label="职务" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <a-select
                  :disabled="disableSubmit"
                  style="width: 100%"
                  placeholder="请选择职务"
                  showSearch
                  optionFilterProp="children"
                  :autoClearSearchValue="false"
                  allowClear
                  v-decorator="['positionId']"
                  :getPopupContainer="(target) => target.parentNode">
                  <a-select-option v-for="(item, index) in positionList" :key="index" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row >
            <a-col :span="colSpan" v-if="showAdminFlag">
              <a-form-item label="是否超管" :labelCol="labelCol" :wrapperCol="wrapperCol">
                <j-dict-select-tag :triggerChange="true" v-decorator="['userIdentity']" dictCode="is_admin" :disabled="disableSubmit"></j-dict-select-tag>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
      </a-form>
    </a-spin>

    <div class="drawer-bootom-button" v-show="!disableSubmit">
      <a-popconfirm title="确定放弃编辑？" @confirm="handleCancel" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading">提交</a-button>
    </div>
  </a-drawer>
</template>

<script>
  // 引入搜索部门弹出框的组件
  import DepartWindow from '@/views/system/depart/modules/DepartWindow.vue'
  import JSelectPosition from '@/components/jeecgbiz/JSelectPosition.vue'
  import { duplicateCheck } from '@/api/api'
  import JImageUpload from '@/components/jeecg/JImageUpload.vue'
  import { queryByTenantId } from '@/views/system/position/service.js'
  import { queryTenantChildList, queryDepartByTenantId } from '@/views/system/user/service'
  import { addUserRole } from '../service';
  import pick from 'lodash.pick';

  export default {
    name: 'AppRoleUserModal',
    components: {
      JImageUpload,
      DepartWindow,
      JSelectPosition
    },
    data () {
      return {
        roleId: '',
        title: '操作',
        modalWidth: 800,
        drawerWidth: 700,
        confirmLoading: false,
        modaltoggleFlag: true,
        confirmDirty: false,
        disableSubmit: false,
        showAdminFlag: false,
        showPassword: true,
        positionList: [],
        roleList: [],
        tenantList: [],
        departTreeData: [],
        departsTreeData: [],
        tenantMap: {},
        departIds: [], // 负责部门id
        visible: false,
        colSpan: 12,
        tenantId: '',
        labelCol: {
          xs: { span: 24 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        },
        bodyStyle: { 'min-height': '500px' },
        form: this.$form.createForm(this),
        url: {
        },
        validatorRules: {
          username: { rules: [{ required: true, message: '请输入账号!' }, { validator: this.validateUsername }] },
          realname: { rules: [{ required: true, message: '请输入姓名!' }, { validator: this.validateRealName }] },
          password: { rules: [{ required: true, pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[~!@#$%^&*()_+`\-={}:";'<>?,./]).{8,16}$/, message: '密码由8-16位数字、大小写字母和特殊符号组成!' }, { validator: this.validateToNextPassword }] },
          confirmpassword: { rules: [{ required: true, message: '请重新输入登录密码!' }, { validator: this.compareToFirstPassword }] },
          phone: { rules: [{ required: true, message: '请输入手机号!' }, { validator: this.validatePhone }] },
          tenant: { rules: [{ required: true, message: '请选择组织!' }, { validator: this.validateSameTenant }] },
          // depart: { rules: [{ required: true, message: '请选择部门!' }] },
          workNo: { rules: [{ validator: this.validateWorkNo }] },
          email: { rules: [{ validator: this.validateEmail }] },
          telephone: { rules: [{ pattern: /^\+?[1-9]\d{0,14}$/, message: '请输入正确格式的座机号！' }] }
        }
      }
    },
    created () {
    },
    computed: {
    },
    methods: {
      add(tenantId) {
        this.form.resetFields();
        this.visible = true;
        this.resetScreenSize();
        this.tenantId = tenantId;
        this.initTenantList(undefined, tenantId);
        // 清空数据
        this.departTreeData = [];
        this.departsTreeData = [];
        this.positionList = [];
      },
      edit(record, tenantId) {
        let that = this;
        this.userId = record.userId;
        this.tenantId = tenantId;
        this.showAdminFlag = false;
        this.positionList = [];
        this.tenantList = [];
        this.departTreeData = [];
        this.departsTreeData = [];
        this.tenantMap = {};
        this.departIds = [];
        this.model = {};
        this.form.resetFields()
        this.model = Object.assign({}, record)
        this.model.departId = record.belongDepartIds ? record.belongDepartIds.split(',') : undefined;
        this.model.departIds = record.departIds ? record.departIds.split(',') : undefined;
        this.model.positionId = record.post;

        this.visible = true;

        if (this.model.id) {
          this.initTenantList(function () {
            that.initPositionList(that.model.tenantId);
            that.initDepartList(that.model.tenantId);
            if (that.model.belongDepartIds) {
              that.changeDepart(that.model.belongDepartIds.split(','), that.model.departNames.split(','))
            } else {
              that.model.departIds = [];
            }
            that.showAdminFlag = !that.tenantMap[that.model.tenantId].hasAdmin || that.tenantMap[that.model.tenantId].adminId === that.model.userId;
            that.$nextTick(() => {
              setTimeout(() => {
                that.form.setFieldsValue(pick(that.model, 'username', 'realname', 'phone', 'sex', 'telephone', 'email', 'birthday', 'tenantId', 'departId', 'departIds', 'workNo', 'positionId', 'userIdentity', 'avatar'));
              }, 5)
            })
          }, tenantId);
        } else {
          this.initTenantList(undefined, tenantId);
        }
      },

      initTenantList(event, tenantId) {
        queryTenantChildList(tenantId).then(res => {
          if (res.success) {
            this.tenantList = res.result
            this.tenantList.forEach((item) => {
              this.tenantMap[item.id] = item;
            })
            if (event) {
              event();
            }
          }
        })
      },
      changeTenant(tenantId) {
        this.initPositionList(tenantId);
        this.initDepartList(tenantId);
        this.form.resetFields('departId', '');
        this.form.resetFields('departIds', '');
        this.form.resetFields('positionId', '');
        this.departsTreeData = [];
        this.showAdminFlag = !this.tenantMap[tenantId].hasAdmin;
        if (this.showAdminFlag) {
          this.$nextTick(() => {
            this.form.setFieldsValue({
              userIdentity: 1
            })
          });
        }
      },
      initPositionList(tenantId) {
        if (tenantId) {
          queryByTenantId(tenantId).then(res => {
            if (res.success) {
              this.positionList = res.result;
            }
          })
        } else {
          this.positionList = [];
        }
      },
      initDepartList(tenantId) {
        if (tenantId) {
          queryDepartByTenantId(tenantId).then(res => {
            if (res.success) {
              this.departTreeData = res.result
            }
          })
        } else {
          this.departTreeData = []
        }
      },
      changeDepart(departIds, labels) {
        let that = this
        this.form.resetFields('departIds', '');
        if (departIds && departIds.length > 0) {
          that.departsTreeData = [];
          departIds.forEach(function (item, i) {
            that.departsTreeData.push({ value: item, label: labels[i] })
          })
        } else {
          that.departsTreeData = [];
        }
        // that.form.setFieldsValue({ ['tenants[' + index + '][departIds]']: undefined })
      },
      // 窗口最大化切换
      toggleScreen() {
        if (this.modaltoggleFlag) {
          this.modalWidth = window.innerWidth;
        } else {
          this.modalWidth = 800;
        }
        this.modaltoggleFlag = !this.modaltoggleFlag;
      },
      close () {
        this.$emit('close');
        this.visible = false;
        this.disableSubmit = false;
        this.departIds = [];
        this.showPassword = false;
        this.$nextTick(() => {
          this.showPassword = true;
        })
      },
      handleSubmit () {
        let that = this;
        that.form.validateFields((err, values) => {
          if (!err) {
            values.roles = [this.roleId];
            addUserRole(values).then(res => {
              if (res.success) {
                this.close();
                that.$message.success(res.message);
                this.$emit('ok');
              } else {
                this.$message.error(res.message);
              }
            });
          }
        })
      },
      handleCancel () {
        this.close()
      },
      validateToNextPassword  (rule, value, callback) {
        const form = this.form;
        const confirmpassword = form.getFieldValue('confirmpassword');
        if (value && confirmpassword && value !== confirmpassword) {
          callback('两次输入的密码不一样！');
        }
        if (value && this.confirmDirty) {
          form.validateFields(['confirmpassword'], { force: true })
        }
        callback();
      },
      compareToFirstPassword  (rule, value, callback) {
        const form = this.form;
        if (value && value !== form.getFieldValue('password')) {
          callback('两次输入的密码不一样！');
        } else {
          this.confirmDirty = false
          form.validateFields(['password'], { force: true })
          callback()
        }
      },
      validatePhone(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (new RegExp(/^1[3|4|5|7|8|9][0-9]\d{8}$/).test(value)) {
            var params = {
              tableName: 'sys_user',
              fieldName: 'phone',
              fieldVal: value,
              dataId: this.userId,
              delFlag: 'del_flag',
              delFlagValue: 0
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback('手机号已存在!')
              }
            })
          } else {
            callback('请输入正确格式的手机号码!');
          }
        }
      },
      validateUsername(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 21) {
            var params = {
              tableName: 'sys_user',
              fieldName: 'username',
              fieldVal: value,
              dataId: this.userId,
              delFlag: 'del_flag',
              delFlagValue: 0
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback('用户名已存在!')
              }
            });
          } else {
            callback('用户名长度不能大于20个字符!')
          }
        }
      },
      validateRealName(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 21) {
            callback()
          } else {
            callback('用户姓名长度不能大于20个字符!')
          }
        }
      },
      validateEmail(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 51) {
            if (new RegExp(/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/).test(value)) {
              var params = {
                tableName: 'sys_user',
                fieldName: 'email',
                fieldVal: value,
                dataId: this.userId
              };
              duplicateCheck(params).then((res) => {
                console.log(res)
                if (res.success) {
                  callback()
                } else {
                  callback('邮箱已存在!')
                }
              })
            } else {
              callback('请输入正确格式的邮箱!')
            }
          } else {
            callback('邮箱的长度不能大于50个字符!')
          }
        }
      },
      validateWorkNo(rule, value, callback) {
        if (!value) {
          callback()
        } else {
          if (value.length < 16) {
            var params = {
              tableName: 'sys_user_tenant',
              fieldName: 'work_no',
              fieldVal: value,
              tenantId: this.tenantId,
              dataId: this.id
            };
            duplicateCheck(params).then((res) => {
              if (res.success) {
                callback()
              } else {
                callback('工号已存在!')
              }
            })
          } else {
            callback('工号长度小于15个字符！')
          }
        }
      },
      handleConfirmBlur  (e) {
        const value = e.target.value;
        this.confirmDirty = this.confirmDirty || !!value
      },
      // 根据屏幕变化,设置抽屉尺寸
      resetScreenSize() {
        let screenWidth = document.body.clientWidth;
        if (screenWidth < 500) {
          this.drawerWidth = screenWidth;
        } else {
          this.drawerWidth = 700;
        }
      }
    }
  }
</script>

<style scoped>
  .avatar-uploader > .ant-upload {
    width:104px;
    height:104px;
  }
  .ant-upload-select-picture-card i {
    font-size: 49px;
    color: #999;
  }

  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .ant-table-tbody .ant-table-row td{
    padding-top:10px;
    padding-bottom:10px;
  }

  .drawer-bootom-button {
    position: absolute;
    bottom: -8px;
    width: 100%;
    border-top: 1px solid #e8e8e8;
    padding: 10px 16px;
    text-align: right;
    left: 0;
    background: #fff;
    border-radius: 0 0 2px 2px;
  }
</style>
